package com.tjec.framework.security.service;

import com.tjec.common.constant.Constants;
import com.tjec.common.exception.CustomException;
import com.tjec.common.exception.user.CaptchaException;
import com.tjec.common.exception.user.CaptchaExpireException;
import com.tjec.common.exception.user.UserException;
import com.tjec.common.exception.user.UserPasswordNotMatchException;
import com.tjec.common.utils.MessageUtils;
import com.tjec.common.utils.SFtpUtil;
import com.tjec.common.utils.StringUtils;
import com.tjec.framework.manager.AsyncManager;
import com.tjec.framework.manager.factory.AsyncFactory;
import com.tjec.framework.redis.RedisCache;
import com.tjec.framework.security.LoginUser;
import com.tjec.project.system.domain.SysUser;
import com.tjec.project.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

/**
 * 登录校验方法
 *
 * @author tjec
 */
@Component
public class SysLoginService {
    private static final Logger log = LoggerFactory.getLogger(SFtpUtil.class);

    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private SysPermissionService permissionService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        //移除图片验证码验证
        /*SString verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        tring captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }*/
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }

    public String login(String username) {

        LoginUser loginUser = new LoginUser();
        //根据手机号获取用户名
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);

        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        loginUser.setUser(sysUser);
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 手机号登录验证
     *
     * @param phonenumber 手机号
     * @param code        验证码
     * @param uuid        唯一标识
     * @return 结果
     */
    public String phonenumberLogin(String phonenumber, String code, String uuid) {

        String verifyKey = Constants.CAPTCHA_CODE_KEY + phonenumber + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);

        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(phonenumber, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(phonenumber, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
        LoginUser loginUser = new LoginUser();
        //根据手机号获取用户名
        SysUser sysUser = iSysUserService.selectUserByPhonenumber(phonenumber);
        if (null == sysUser) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(phonenumber, Constants.LOGIN_FAIL, MessageUtils.message("user.mobile.not.exists")));
            throw new UserException("user.mobile.not.exists", null);
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(phonenumber, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        loginUser.setUser(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        loginUser.setPermissions(permissions);

        redisCache.deleteObject(verifyKey);
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 门户单点登录
     *
     * @param jobNo 工号
     * @return 结果
     */
    public String portalSsoLogin(String jobNo) {

    	if (!StringUtils.isNotBlank(jobNo)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(jobNo, Constants.LOGIN_FAIL, MessageUtils.message("user.not.exist")));
            throw new UserException("user.not.exist", null);
        }

        LoginUser loginUser = new LoginUser();
        //根据工号获取用户名
        SysUser sysUser = iSysUserService.selectUserByJobNo(jobNo);
        if (sysUser==null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(jobNo, Constants.LOGIN_FAIL, MessageUtils.message("user.not.exist")));
            throw new UserException("user.not.exist", null);
        }else{
            log.info("单点登录门户。。。。-"+sysUser.getUserName());
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(sysUser.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        }

        loginUser.setUser(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        loginUser.setPermissions(permissions);
        // 生成token
        return tokenService.createToken(loginUser);
    }
}
